import base64
from Crypto.Cipher import PKCS1_v1_5 as PKCS1_cipher
from Crypto.PublicKey import RSA

def get_key_pair():
    rsa_value = rsa_cache.get(cache_key)
    if rsa_value is None:
        lock.acquire()
        rsa_value = rsa_cache.get(cache_key)
        if rsa_value is not None:
            return rsa_value
        try:
            rsa_value = get_key_pair_by_sql()
            rsa_cache.set(cache_key, rsa_value)
        finally:
            lock.release()
    return rsa_value
def get_key_pair_by_sql():
    system_setting = QuerySet(SystemSetting).filter(type=SettingType.RSA.value).first()
    if system_setting is None:
        kv = generate()
        system_setting = SystemSetting(type=SettingType.RSA.value,
                                       meta={'key': kv.get('key').decode(), 'value': kv.get('value').decode()})
        system_setting.save()
    return system_setting.meta
def rsa_long_decrypt(message, pri_key: str | None = None, length=256):
    """
    超长文本解密，默认不加密
    :param  message:    需要解密的数据
    :param  pri_key:    秘钥
    :param  length :     1024bit的证书用128，2048bit证书用256位
    :return: 解密后的数据
    """
    if pri_key is None:
        pri_key = get_key_pair().get('value')
    cipher = PKCS1_cipher.new(RSA.importKey(pri_key, passphrase=secret_code))
    base64_de = base64.b64decode(message)
    res = []
    for i in range(0, len(base64_de), length):
        res.append(cipher.decrypt(base64_de[i:i + length], 0))
    return b"".join(res).decode()
str = "elzRarJUK/06Yeb0QJKCzIPFthxtu28bggGMYUlJK3YMB+/BMIh8kK7RZgP+Px0Mq21A1kDE/W4JqvCtagf8zUsNDYct1rM5o54bjpU8VdOq2oq2RXnMVr8NNZyIJHkYPHDxy3uveoxX3QpnHjewjEho4SxKTb4ZBxZ9TGMb8aKhOKyf7Os/pwOCQ7MbD/lpmLODkQU86U/JnGUear02QJF7HbG07c2acYy1JOEV1kMMBnpCENbjpbpMnyi+b8hb4PxYi7r/isNv0t0IZbyoHUMrHA9nnc/EzJHf1sJQwCfTUjTgkqaaPJibzzu32v59q8QwcWZuprs+CopT5/kdaQ=="
str = base64.b64decode(str)
print(str)